package ar.com.e2solver.solver.operator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import ar.com.e2solver.exception.BusinessException;
import ar.com.e2solver.solver.Individual;
import ar.com.e2solver.solver.Population;
import ar.com.e2solver.solver.RandomConstants;
import ar.com.e2solver.solver.operator.impl.RotateMutationOperator;
import ar.com.e2solver.solver.operator.impl.SwapMutationOperator;

public class HillClimbing {

	private static HillClimbing instance = new HillClimbing();
	
	private HillClimbing(){}
	
	public static HillClimbing getInstance(){
		return instance;
	}

	public List<Individual> climb(List<Individual> selectedIndividuals) throws BusinessException {
		List<Individual> result = new ArrayList<Individual>();
		
		for (Iterator<Individual> iterator = selectedIndividuals.iterator(); iterator.hasNext();) {
			Individual individual = iterator.next();
			result.add(climb(individual));
		}
		
		return result;
	}

	private Individual climb(Individual individual) throws BusinessException {
		Individual result = individual;
		
		for (int i = 0; i < 1000; i++) {	
			Population population = new Population();
			
			for (int j = 0; j < 100; j++) {
				if(RandomConstants.RANDOM.nextBoolean()){
					population.add(SwapMutationOperator.getInstance().operate(result));
				} else {
					population.add(RotateMutationOperator.getInstance().operate(result));
				}
			}
			result = population.getBestIndividual();
		}
		
		return result;
	}
	
	
}
